public class LeetCode930 {
    public static void main(String[] args) {
        int[] nums = {0, 0, 0, 0, 0, 0, 1, 0, 0, 0};
        int target = 0;

        System.out.println(numSubarraysWithSum(nums, target));
    }

    public static int numSubarraysWithSum(int[] nums, int goal) {
        int n = nums.length;

        // left1与left2之间夹着的是很多个0
        int left1 = 0, left2 = 0, right = 0;
        int sum1 = 0, sum2 = 0;
        int res = 0;

        // 右边界
        while (right < n) {
            sum1 += nums[right];
            // sum1 要等于 goal-1
            while (left1 <= right && sum1 > goal) {
                sum1 -= nums[left1];
                left1++;
            }
            sum2 += nums[right];
            // sum2 要等于 goal
            while (left2 <= right && sum2 >= goal) {
                sum2 -= nums[left2];
                left2++;
            }
            // 其中的每个0都能算一种情况
            res += left2 - left1;
            // 右指针右移
            right++;
        }
        return res;
    }
}
